<?php
/**
 * 极简随手记
 * ============================================================================
 * 版权所有 2024-2099 www.alipay168.cn，并保留所有权利。
 * 网站地址: https://www.alipay168.cn
 * ============================================================================
 * Author: 草上飞
 * Email: wei@alipay16.cn
 * QQ: 2719875001
 * Date: 2024/12/29
 * 描述:
 */

namespace app\result\extend;

use app\model\extend\PCashbook;
use app\model\extend\PCashbookUser;
use app\model\user\Cashflows;
use app\model\user\User;
use app\result\BaseResult;

class CashbookResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new PCashbook();
    }

    public function get_default_cashbook($user_id)
    {
        $model = new PCashbookUser();
        $data = $model->data_get(['user_id' => $user_id], 'cashbook_id', 'is_default desc,id desc');
        if (!$data) {
            return [];
        }
        $cashbook = $this->model->data_get(['cashbook_id' => $data['cashbook_id'], 'del_time' => 0], 'name,cashbook_id');
        if (!$cashbook) {
            return [];
        }
        return $cashbook;
    }

    public function list_option($user_id, $args = [], $from_ready = false)
    {
        $where = [['a.user_id', '=', $user_id], ['b.del_time', '=', 0]];
        $filed = 'a.cashbook_id as value,b.name as label,b.user_id as owner_id';
        $data = (new PCashbookUser())->alias('a')
            ->join('p_cashbook b', 'a.cashbook_id=b.cashbook_id', 'left')
            ->where($where)
            ->field($filed)
            ->order('a.is_default desc,a.sort desc,a.id desc')
            ->select()
            ->toArray();
        if ($data) {
            foreach ($data as &$v) {
                $v['is_owner'] = $v['owner_id'] == $user_id;
                $v['label'] = $v['label'] . '(' . ($v['is_owner'] ? '自建' : '共享') . ')';
            }
            unset($v);
        }
        return $data;
    }


    public function list($user_id, $args = [])
    {
        $page = $args['page'] ?? 1;
        $limit = $args['limit'] ?? 10;
        $keyword = $args['keyword'] ?? '';
        $where = [['a.user_id', '=', $user_id], ['b.del_time', '=', 0]];
        if ($keyword) {
            $where[] = ['b.name', 'like', "%{$keyword}%"];
        }
        $filed = 'a.cashbook_id,a.sort,a.is_default,b.name,b.remark,b.sort,b.cashbook_sn,b.created_at,b.user_id as owner_id';
        $data = (new PCashbookUser())->alias('a')
            ->join('p_cashbook b', 'a.cashbook_id=b.cashbook_id', 'left')
            ->where($where)
            ->field($filed)
            ->order('a.is_default desc,a.sort desc,a.id desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
        if ($data) {
            $modelCashbookUser = new PCashbookUser();
            $modelCashFlows = new Cashflows();
            foreach ($data as &$v) {
                $v['is_owner'] = $v['owner_id'] == $user_id;
                $v['user_count'] = $modelCashbookUser->data_count(['cashbook_id' => $v['cashbook_id']]);
                $v['bill_count'] = $modelCashFlows->data_count(['cashbook_id' => $v['cashbook_id']]);
            }
            unset($v);
        }

        return self::success_return('success', [
            'list' => $data,
        ]);
    }

    public function get($user_id, $args = [])
    {
        $cashbook_id = $args['cashbook_id'] ?? 0;
        if (!$cashbook_id) {
            return self::error_return('数据错误');
        }
        $data = $this->model->data_get(['cashbook_id' => $cashbook_id, 'del_time' => 0]);
        $userRelation = (new PCashbookUser())->data_get(['cashbook_id' => $cashbook_id, 'user_id' => $user_id]);
        if (!$userRelation) {
            return self::error_return('没有权限');
        }
        $data['sort'] = $userRelation['sort'];
        $data['is_default'] = boolval($userRelation['is_default']);
        $data['is_owner'] = $data['user_id'] == $user_id;
        $data['from_join'] = $data['is_owner'] ? 0 : 1;
        return self::success_return('success', [
            'info' => $data,
        ]);
    }

    public function save($user_id, $args)
    {
        $cashbook_id = $args['cashbook_id'] ?? 0;
        $name = $args['name'] ?? '';
        $remark = $args['remark'] ?? '';
        if (mb_strlen($remark, 'utf-8') > 200) {
            return self::error_return('备注不能超过200字');
        }
        if (!$name) {
            return self::error_return('请填写账本名称');
        }

        if ($cashbook_id) {
            $data = $this->model->data_get(['cashbook_id' => $cashbook_id, 'user_id' => $user_id, 'del_time' => 0]);
            if (!$data || $data['user_id'] != $user_id) {
                return self::error_return('只能修改自己的数据');
            }
            $cashbook_sn = $data['cashbook_sn'];
        } else {
            $cashbook_sn = $this->get_cashbook_sn();
        }
        $baseData = [
            'name' => $name,
            'remark' => $remark,
            'user_id' => $user_id,
            'cashbook_sn' => $cashbook_sn,
        ];
        if (!empty($args['is_default'])) {
            (new PCashbookUser())->data_update(['user_id' => $user_id], ['is_default' => 0]);
        }
        if ($cashbook_id) {
            $res = $this->model->data_update(['cashbook_id' => $cashbook_id], $baseData);
            $res = (new PCashbookUser())->data_update(['cashbook_id' => $cashbook_id], [
                'sort' => $args['sort'] ?? 0,
                'is_default' => !empty($args['is_default']) ? 1 : 0,
            ]);
        } else {
            $cashbook_id = $this->model->data_add($baseData);
            $res = (new PCashbookUser())->data_add([
                'user_id' => $user_id,
                'cashbook_id' => $cashbook_id,
                'sort' => $args['sort'] ?? 0,
                'is_default' => !empty($args['is_default']) ? 1 : 0,
            ]);
        }
        if (!$res) {
            return self::error_return('保存失败');
        }
        return self::success_return('保存成功');
    }

    public function get_cashbook_sn()
    {
        //15位随机数字
        while (true) {
            $cashbook_sn = mt_rand(100000000000000, 999999999999999);
            $data = $this->model->data_get(['cashbook_sn' => $cashbook_sn], 'cashbook_sn');
            if (!$data) {
                break;
            }
        }
        return $cashbook_sn;
    }

    public function delete($user_id, $args)
    {
        $cashbook_id = $args['cashbook_id'] ?? 0;
        if (!$cashbook_id) {
            return self::error_return('请选择要删除的数据');
        }
        $data = $this->model->data_get(['cashbook_id' => $cashbook_id, 'del_time' => 0]);
        if (!$data || $data['user_id'] != $user_id) {
            return self::error_return('只能删除自己创建的账本');
        }
        $this->model->data_del_soft(['cashbook_id' => $cashbook_id], 'del_time', time());
        return self::success_return('删除成功');
    }

    public function join($user_id, $args)
    {
        $cashbook_sn = $args['cashbook_sn'] ?? 0;
        if (!$cashbook_sn) {
            return self::error_return('请输入账本编号');
        }
        $data = $this->model->data_get(['cashbook_sn' => $cashbook_sn, 'del_time' => 0]);
        if (!$data) {
            return self::error_return('没有找到该账本');
        }
        if ($data['user_id'] == $user_id) {
            return self::error_return('不能加入自己的账本');
        }
        $baseData = [
            'user_id' => $user_id,
            'cashbook_id' => $data['cashbook_id'],
            'sort' => $args['sort'] ?? 0,
            'is_default' => !empty($args['is_default']) ? 1 : 0,
        ];
        if ($baseData['is_default']) {
            (new PCashbookUser())->data_update(['user_id' => $user_id], ['is_default' => 0]);
        }
        $has = (new PCashbookUser())->data_get(['user_id' => $user_id, 'cashbook_id' => $data['cashbook_id']]);
        if ($has) {
            $res = (new PCashbookUser())->data_update(['id' => $has['id']], $baseData);
        } else {
            $res = (new PCashbookUser())->data_add($baseData);
            if (!$res) {
                return self::error_return('加入失败');
            }
        }
        return self::success_return('保存成功');
    }

    public function fetch($user_id, $args)
    {
        $cashbook_sn = $args['cashbook_sn'] ?? 0;
        if (!$cashbook_sn) {
            return self::error_return('请输入账本编号');
        }
        $data = $this->model->data_get(['cashbook_sn' => $cashbook_sn, 'del_time' => 0]);
        if (!$data) {
            return self::error_return('没有找到该账本');
        }
        $data['username'] = (new User())->get_value(['user_id' => $data['user_id']], 'username');
        $has = (new PCashbookUser())->data_get(['user_id' => $user_id, 'cashbook_id' => $data['cashbook_id']]);
        $data['from_join'] = 1;//是否可以加入
        return self::success_return('success', [
            'info' => $data,
            'has_joined' => (bool)$has,
        ]);
    }

    public function user_list($user_id, $args)
    {
        $cashbook_id = $args['cashbook_id'] ?? 0;
        if (!$cashbook_id) {
            return self::error_return('请选择账本');
        }
        $data = $this->model->data_get(['cashbook_id' => $cashbook_id, 'del_time' => 0]);
        if (!$data) {
            return self::error_return('没有找到该账本');
        }
        $joined = (new PCashbookUser())->data_get(['user_id' => $user_id, 'cashbook_id' => $cashbook_id]);
        if (!$joined) {
            return self::error_return('仅限查看已加入的账本成员');
        }
        $list = (new PCashbookUser())->alias('a')
            ->join('user b', 'a.user_id=b.user_id', 'left')
            ->field('a.id,a.cashbook_id,b.username,b.account,b.avatar,a.user_id')
            ->where(['a.cashbook_id' => $cashbook_id])
            ->order('a.id desc')
            ->select();
        if ($list) {
            $list = $list->toArray();
            $modelCashFlows = new Cashflows();
            foreach ($list as &$item) {
                $item['is_owner'] = $item['user_id'] == $data['user_id'] ? 1 : 0;
                $item['count'] = $modelCashFlows->data_count(['user_id' => $item['user_id'], 'cashbook_id' => $cashbook_id]);
                $item['unbind'] = $data['user_id'] == $user_id && !$item['is_owner'];
                unset($item['user_id']);
            }
            unset($item);
            usort($list, function ($a, $b) {
                return $b['is_owner'] - $a['is_owner'];
            });
        }
        return self::success_return('success', [
            'list' => $list
        ]);
    }

    public function unbind_user($user_id, $args)
    {
        $cashbook_id = $args['cashbook_id'] ?? 0;
        $id = $args['id'] ?? 0;
        if (!$cashbook_id) {
            return self::error_return('请选择账本');
        }
        if (!$id) {
            return self::error_return('请选择要解绑的成员');
        }
        $data = $this->model->data_get(['cashbook_id' => $cashbook_id, 'del_time' => 0]);
        if (!$data) {
            return self::error_return('没有找到该账本');
        }
        if ($data['user_id'] != $user_id) {
            return self::error_return('仅限解绑自己创建的账本成员');
        }
        $res = (new PCashbookUser())->data_del(['id' => $id]);
        return $res ? self::success_return('解绑成功') : self::error_return('解绑失败');
    }


}
